package com.jf.map;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.jf.demo.Mainmenu;
import com.jf.demo.MyAlreadyOrder;
import com.jf.demo.R;
import com.jf.map.NearbyServMap.MyOverlay;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.sys.android.util.FinalUntil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

/**
 * 定位附近快递员
 * 
 */
public class NearbyUser extends Activity {

	private enum E_BUTTON_TYPE {
		LOC, COMPASS, FOLLOW
	}

	private int[] messImage = FinalUntil.messImage;

	MyOverlay mOverlay = null;

	private ArrayList<OverlayItem> mItems = null;
	// 定位相关
	LocationClient mLocClient;
	LocationData locData = null;
	public MyLocationListenner myListener = new MyLocationListenner();

	// 定位图层
	locationOverlay myLocationOverlay = null;
	// 弹出泡泡图层
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	public TextView popupText = null;// 泡泡view
	private View viewCache = null;
	private View popupInfo = null;
	private View popupLeft = null;
	private View popupLeftImage = null;
	private View popupRight = null;
	private TextView popupRightImage = null;

	// 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	// 如果不处理touch事件，则无需继承，直接使用MapView即可
	MapView mMapView = null; // 地图View
	private MapController mMapController = null;

	// UI相关
	OnCheckedChangeListener radioButtonListener = null;
	Button requestLocButton = null;
	boolean isRequest = false;// 是否手动触发请求定位
	boolean isFirstLoc = true;// 是否首次定位
	public BMapManager mBMapMan;

	public TextView nearbyUserName;

	private Button button1;

	private Button button2;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		mBMapMan = new BMapManager(getApplication());
		mBMapMan.init(null);
		// 注意：请在试用setContentView前初始化BMapManager对象，否则会报错
		setContentView(R.layout.nearby_user);
		CharSequence titleLable = "定位功能";
		setTitle(titleLable);

		mMapView = (MapView) findViewById(R.id.bmapsView);// 获取地图控件

		mMapController = mMapView.getController();
		mMapView.getController().setZoom(18);
		mMapView.getController().enableClick(true);
		mMapView.setBuiltInZoomControls(true);

		// 定位初始化
		mLocClient = new LocationClient(this);
		locData = new LocationData();
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.disableCache(false);
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		// 定位图层初始化
		myLocationOverlay = new locationOverlay(mMapView);
		// 设置定位数据
		myLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		// 修改定位数据后刷新图层生效
		mMapView.refresh();

		button1 = (Button) findViewById(R.id.sendnearbyUser);
		button2 = (Button) findViewById(R.id.callnearbyUser);
		button1.setVisibility(View.INVISIBLE);
		button2.setVisibility(View.INVISIBLE);
	}

	public void finishNearbyUser(View v) {
		this.finish();
	}

	/**
	 * 手动触发一次定位请求
	 */
	public void requestLocClick() {
		isRequest = true;
		mLocClient.requestLocation();
		Toast.makeText(NearbyUser.this, "正在定位……", Toast.LENGTH_SHORT).show();
	}

	/**
	 * 修改位置图标
	 * 
	 * @param marker
	 */
	public void modifyLocationOverlayIcon(Drawable marker) {
		// 当传入marker为null时，使用默认图标绘制
		myLocationOverlay.setMarker(marker);
		// 修改图层，需要刷新MapView生效
		mMapView.refresh();
	}

	/**
	 * 创建弹出泡泡图层
	 */
	public void createPaopao() {
		/**
		 * 向地图添加自定义View.
		 */
		viewCache = getLayoutInflater()
				.inflate(R.layout.custom_text_view, null);
		popupInfo = (View) viewCache.findViewById(R.id.popinfo);
		popupLeftImage = (View) viewCache.findViewById(R.id.popleftImage);
		// popupLeft = (View) viewCache.findViewById(R.id.popleft);
		// popupRight = (View) viewCache.findViewById(R.id.popright);
		popupText = (TextView) viewCache.findViewById(R.id.textcache);
		popupRightImage = (TextView) viewCache.findViewById(R.id.mapImage);
		/**
		 * 弹出的气泡中点击事件的监听
		 */
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {

				if (index == 0) {
					// 更新item位置菜单按钮中的点击事件

				} else if (index == 2) {
					// 更新图标
					Intent intent = new Intent(NearbyUser.this,
							MyAlreadyOrder.class);
					startActivity(intent);
				}
			}
		};
		pop = new PopupOverlay(mMapView, popListener);
		// MyLocationMapView.pop = pop;
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			locData.accuracy = location.getRadius();
			// 此处可以设置 locData的方向信息, 如果定位 SDK 未返回方向信息，用户可以自己实现罗盘功能添加方向信息。
			locData.direction = location.getDerect();
			// 更新定位数据
			myLocationOverlay.setData(locData);
			// 更新图层数据执行刷新后生效
			// mMapView.refresh();
			// 是手动触发请求或首次定位时，移动到定位点
			if (isRequest || isFirstLoc) {
				// 移动地图到定位点
				Log.d("LocationOverlay", "receive location, animate to it");
				mMapController.animateTo(new GeoPoint(
						(int) (locData.latitude * 1e6),
						(int) (locData.longitude * 1e6)));
				isRequest = false;
				myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);

				GraphicsOverlay graphicsOverlay = new GraphicsOverlay(mMapView);
				mMapView.getOverlays().add(graphicsOverlay);

				mapViewList(locData.longitude, locData.latitude);

			}
			// 首次定位完成
			isFirstLoc = false;
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	// 继承MyLocationOverlay重写dispatchTap实现点击处理
	public class locationOverlay extends MyLocationOverlay {

		public locationOverlay(MapView mapView) {
			super(mapView);
			// TODO Auto-generated constructor stub
		}

		/**
		 * 点击自已位置的图标时显示气泡
		 */
		@Override
		protected boolean dispatchTap() {
			// TODO Auto-generated method stub
			// 处理点击事件,弹出泡泡
			// popupText.setBackgroundResource(R.drawable.popup);
			popupText.setText("我的位置");
			pop.showPopup(BMapUtil.getBitmapFromView(popupText), new GeoPoint(
					(int) (locData.latitude * 1e6),
					(int) (locData.longitude * 1e6)), 8);
			return true;
		}

	}

	private String phoneNow;

	public class MyOverlay extends ItemizedOverlay {

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}

		/**
		 * 点击地图上气泡时候触发
		 */
		@Override
		public boolean onTap(int index) {
			button1.setVisibility(View.VISIBLE);
			button2.setVisibility(View.VISIBLE);

			OverlayItem item = mItems.get(index);
			nearbyUserName = (TextView) findViewById(R.id.nearbyUserName);

			String str[] = getItem(index).getSnippet().split("&");
			int msImg = Integer.parseInt(str[0].toString());
			phoneNow = str[1];
			nearbyUserName.setText(getItem(index).getTitle());
			popupText.setText(getItem(index).getTitle());
			popupRightImage.setBackgroundResource(messImage[msImg]);
			Bitmap[] bitMaps = { BMapUtil.getBitmapFromView(popupLeftImage),
					BMapUtil.getBitmapFromView(popupInfo),
			// BMapUtil.getBitmapFromView(popupRight)
			};
			pop.showPopup(bitMaps, item.getPoint(), 32);
			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView) {
			if (pop != null) {
				pop.hidePop();
				// mMapView.removeView(button);
			}
			return false;
		}

	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		if (mLocClient != null)
			mLocClient.stop();
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/**
	 * 发布订单
	 */
	public void releaseOrder(View v) {
		switch (v.getId()) {
		case R.id.sendnearbyUser:
			Toast.makeText(v.getContext(), "订单已发布", 0).show();
			break;
		case R.id.callnearbyUser:
			Intent intent = new Intent();
			intent.setAction("android.intent.action.CALL");
			intent.setData(Uri.parse("tel:" + phoneNow));
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	public void mapViewList(Double x, Double y) {
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("louX", x.toString());
		params.addQueryStringParameter("lauY", y.toString());
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, FinalUntil.ServerAddress + "findAround",
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						Log.i("NearbyServ", arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						Log.i("NearbyServ", arg0.result);
						Drawable mark = getResources().getDrawable(
								R.drawable.icon_gcoding);
						mOverlay = new MyOverlay(mark, mMapView);
						try {
							JSONArray jsonarr = new JSONArray(arg0.result);
							for (int x = 0; x < jsonarr.length(); x++) {
								JSONObject jsonobj = jsonarr.getJSONObject(x);
								double mLat = jsonobj.getDouble("mapY");
								double mLon = jsonobj.getDouble("mapX");
								String str = jsonobj.getString("company")
										+ "\n" + jsonobj.getString("realname");
								GeoPoint p = new GeoPoint((int) (mLat * 1E6),
										(int) (mLon * 1E6));
								OverlayItem item = new OverlayItem(p, str,
										jsonobj.getString("brand") + "&"
												+ jsonobj.getString("username"));
								mOverlay.addItem(item);
							}
							mItems = new ArrayList<OverlayItem>();
							mItems.addAll(mOverlay.getAllItem());
							mMapView.getOverlays().add(mOverlay);
							mMapView.refresh();
							// 创建 弹出泡泡图层
							createPaopao();
						} catch (Exception e) {
							Log.i("NearbyServ", e.toString());
						}
					}
				});
	}
}
